package com.jk.controller;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jk.entity.*;
import com.jk.service.UserService;
import com.jk.util.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map;

/**
 * @author 周慧茹
 * 创建时间 2018/4/11  19:43
 * 邮箱 960297232@qq.com
 */
@RestController
@RequestMapping("/user")
public class ShoppingController {

    @Resource
    private UserService userService;



    @PostMapping
    @RequestMapping("/querysolr")
    public  String  querysolr(Integer curr,Integer  limit,String  shopname){

        System.out.println(shopname);

        int start=(curr-1)*limit; //开始条数  limit每页查几条
        //拿到连接
        HttpSolrClient solrClient = SolrClient.getSolrClient();
        //新建查询
        SolrQuery solrQuery = new SolrQuery();

        if(shopname!=null){
            SolrQuery solrQuery1 = solrQuery.setQuery("shopname:"+shopname);
        }else{
            // 查询条件
            SolrQuery solrQuery1 = solrQuery.setQuery("*:*");
        }
        solrQuery.set("shards","http://localhost:8082/solr/shordemo2,http://localhost:8082/solr/shordemo2copy");
        solrQuery.setStart(start);
        solrQuery.setRows(limit);
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("shopname");
        solrQuery.setHighlightSimplePre("<font color='red'>");//渲染标签
        solrQuery.setHighlightSimplePost("</font>");//渲染标
        QueryResponse response = null;
        List<ShopCar> list= null;
        try {
            response = solrClient.query(solrQuery);
            list = response.getBeans(ShopCar.class);
            if(shopname!=null){
                //遍历的高亮map  最外层的key 其实就是当前商品的id  内层为 商品的字段属性，内层为具体商品
                Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
                for (int i = 0; i < list.size(); i++) {
                    //省掉一层循环， 可以直接返回list
                    List<String> shopname1 = highlighting.get(list.get(i).getShopid()).get("shopname");

                    if(shopname1.size()>0){
                        list.get(i).setShopname(shopname1.get(0));
                    }

                }

            }



        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        for (int i = 0; i < list.size(); i++) {
            if(list.size()>0){
                ShopCar shopCar2 = list.get(i);

                shopCar2.setWy("<button onclick=shopPingCar('"+shopCar2.getShopid()+"')>&#xe657;</button>" +
                        "&nbsp;&nbsp;&nbsp;<button onclick=shopping('"+shopCar2.getShopid()+"') class=layui-icon style=font-size: 30px; color: #FF5722;>&#xe65e;</button>" +
                        "&nbsp;&nbsp;&nbsp;<button onclick=details('"+shopCar2.getShopid()+"') class=layui-icon style=font-size: 30px; color: #5FB878;>&#xe63a;</button>");
            }
        }
        Map map=new HashMap();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", list.size());
        map.put("data", list);
        System.out.println(JSON.toJSONString(map));
        return JSON.toJSONString(map);
    }


    /**
    *@author 周慧茹
    *邮箱 960297232@qq.com
     * 用来查询返回到前台的购物车
    */
    @GetMapping
    @RequestMapping("/queryShopCarbyid")
    public   HashMap<String, List<Shop>>  queryShopCarbyid(String  ids,HttpServletRequest request){

        System.out.println("ids = [" + ids + "]");
        User user =  new  User();
        user.setUsername("猜我是谁");
        user.setUserpass("123");
        user.setUserid("09a2b4f6156b485d804ad25bc2962028");
        request.getSession().setAttribute("user",user);
        String  cookiewy ="596587411222";
        User user1 = (User) request.getSession().getAttribute("user");
        //说明是用户登陆的,去mongodb 查询 真实购物车
        if(Objects.equals(user1.getUserid(),ids)){

            HashMap<String, List<Shop>>   order =  userService.getShopCarbyUserid(ids);

          return   order;
        }  //说明是cookie,去mongodb 查询 虚拟购物车
        else{

            HashMap<String, List<Shop>> dummyOrders =    userService.getShopCarbyCookieid(ids);
            System.out.println(dummyOrders);


            return dummyOrders;
        }




    }


    /**
    *@author 周慧茹
    *邮箱 960297232@qq.com
     * 根据商品id 查询所对应的商品简介
    */
    @GetMapping
    @RequestMapping("/quercommodityByid")
    public String quercommodityByid(String  shopid){

        String  shop  =  userService.quercommodityByid(shopid);

        System.out.println("shop = [" + shop + "]");
        return shop;
    }


    /**
     * 产品分页
     * @param request
     * @param response
     * @param curr
     * @param limit
     * @return
     */
    @RequestMapping(value="/getShopCarList",produces = "text/json;charset=UTF-8")
    public   String  getShopCarList(HttpServletRequest request,HttpServletResponse response,Integer curr,Integer limit){
        int start=(curr-1)*limit; //开始条数  limit每页查几条
        List<ShopCar> list  = userService.getShopCarList(start,limit);
        for (int i = 0; i < list.size(); i++) {
            if(list.size()>0){
                ShopCar shopCar = list.get(i);

                shopCar.setWy("<button onclick=shopPingCar('"+shopCar.getShopid()+"')>&#xe657;</button>" +
                        "&nbsp;&nbsp;&nbsp;<button onclick=shopping('"+shopCar.getShopid()+"') class=layui-icon style=font-size: 30px; color: #FF5722;>&#xe65e;</button>" +
                        "&nbsp;&nbsp;&nbsp;<button onclick=details('"+shopCar.getShopid()+"') class=layui-icon style=font-size: 30px; color: #5FB878;>&#xe63a;</button>");
            }
        }

        Map map=new HashMap();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", list.size());
        map.put("data", list);

        System.out.println(JSON.toJSONString(map));
        return JSON.toJSONString(map);
    }

    /**
    *@author 周慧茹
    *邮箱 960297232@qq.com
     * bootstrap 分页
    */
    @RequestMapping("/pageShoppingcar")
    @GetMapping
    public  String  pageShoppingcar(HttpServletRequest request,HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String offset = request.getParameter("offset");

        String limit = request.getParameter("limit");

        JSONObject json =	userService.pageShopCar(offset,limit);
        System.out.println("json = " + json.toJSONString() + "");

   /*     try {
            response.getWriter().write(json.toJSONString());


        } catch (IOException e) {
            e.printStackTrace();
        }
*/

    return  json.toJSONString();
    }


    /**
    *@author 周慧茹
    *邮箱 960297232@qq.com
     * 模拟登录 之后合并购物车
    */

    @GetMapping
   @RequestMapping("/loginzhr")
   public void   loginzhr(){

       User user =  new  User();
       user.setUsername("猜我是谁");
       user.setUserpass("123");
       user.setUserid("960297232");
       String  cookiewy ="596587411222";

       ResponseMessage   message  = userService.queryShopbycookie(cookiewy,user.getUserid());


   }


   @PostMapping
   @RequestMapping("/add")
   public   void  add(User  user){

       System.out.println("user = [" + user + "]");
   }


    /**
    *@author 周慧茹
    *邮箱 960297232@qq.com
     * 加入购物车
    */
    @RequestMapping("/ShoppingCar")
    @PostMapping
    public ResponseMessage ShoppingCar(String  shopid,Integer shopcount,HttpServletRequest  request,String username,String userid){

  /*       User user =  new  User();
        user.setUsername("猜我是谁");
        user.setUserpass("123");
        user.setUserid("123456789123");
        request.getSession().setAttribute("user",user);*/

        String  cookiewy ="596587411222";

        Integer    mincount=   userService.getShopCountMin(shopid);

        System.out.println("username"+username);
        System.out.println("111111111111111111111111111111111111111111111111111111111111");



          if("".equals(username)&&username!=null&&!"null".equals(username.trim())){
              ResponseMessage   message  =      userService.ShoppingCar(shopid,10,userid,cookiewy);
              message.setId(userid);
              return message;
          }else{
              ResponseMessage   message  =      userService.DummyShoppingCar(shopid,10,cookiewy);
              message.setId(cookiewy);
              return  message;
          }

        }



    @RequestMapping("/addCookie")
    public void addCookie(HttpServletResponse response) throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
        String hostAddress = address.getHostAddress();//192.168.0.121
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        int param= (int)((Math.random()*9+1)*100000);
        String  name = "cookie";
        String  value=dateNowStr+hostAddress+param;
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setMaxAge(1);// 设置为30min 65D47C40018CCBDE82258E0447D7BE5D422080000
        cookie.setPath("/");
        System.out.println("已添加===============");
        response.addCookie(cookie);
    }

   /**
   *@author 周慧茹
   *邮箱 960297232@qq.com
    * 主方法
   */
   /*@PostMapping*/
    public ResponseMessage showCookies(@RequestBody HashMap<String, List<Shop>> map, HttpServletRequest request, HttpServletResponse response) {

      System.out.println("map = [" + map + "]");
       User user =  new  User();
       user.setUsername("周周周");
       user.setUserpass("123");
       user.setUserid("6666666");
       request.getSession().setAttribute("user",user);
       String  cookiewy ="12346789";

         User user1 = (User) request.getSession().getAttribute("user");

         ResponseMessage responsemessage = new ResponseMessage();

         if (user1 != null) {
             ResponseMessage   ResponseMessage =    userService.getService(user1.getUserid(),map,cookiewy);
             return ResponseMessage;

        } else {

/*            Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
            String  cookieid =  null;
            if (null == cookies) {
                System.out.println("没有cookie=========");
            } else {
                for (Cookie cookie : cookies) {

                    cookieid =cookie.getValue();
                }*/
               userService.saveDummyorder(cookiewy,map);
               responsemessage.setResponseno(00);
               responsemessage.setMessage("您没有登陆哦");
               return  responsemessage;

            }

        }









   /**
   *@author 周慧茹
   *邮箱 960297232@qq.com
    * 获取session 测试
   */
    @RequestMapping("/getsession")
    public  void   getsession(HttpServletRequest request){

        User user =  new  User();
        user.setUsername("周周周");
        user.setUserpass("123");
        user.setUserid("65588");
        request.getSession().setAttribute("user",user);


    }

    @RequestMapping("/query")
    @GetMapping
    public  String   query(HttpServletResponse response){


        User user =    userService.query();
        System.out.println("----"+user);
        return  user.toString();
    }

    @PutMapping
    public  void  updatetest(String aaaa){

        System.out.println("收到修改请求"+aaaa);

    }

    @PostMapping
    public void   savetest(String aaaa){

        System.out.println("新增请求"+aaaa);
    }

    @DeleteMapping
    public  void  deletetest(String aaaa){

        System.out.println("删除请求:"+aaaa);
    }

}
